<?php
/**
 * OpenId Login class
 * http://code.google.com/p/lightopenid/wiki/Configuration
 */
require 'lightopenid/openid.php';

/**
 * Use this class to log in using OpenId
 * Uses lightopenid library
 * @author panosbaroudjian
 *
 */
class OpenIdLogin
{
    const GOOGLE_IDENTITY = 'https://www.google.com/accounts/o8/id';
    private $_openid = null;
    private $_id = '';

    /**
     * Creates a new OpenIdLogin object
     * @param string $identity The identity url of the openId provider
     */
    function __construct($identity = OpenIdLogin::GOOGLE_IDENTITY)
    {
        $this->_openid = new LightOpenID();
        $this->_openid->identity = $identity;
        $this->_openid->required = array('contact/email',
                                        'namePerson/first',
                                        'namePerson/last',
                                        'contact/country/home',
                                        'pref/language');
         //http://code.google.com/p/lightopenid/wiki/GettingMoreInformation
    }

    public function getOpenId()
    {
        return $this->_openid;
    }

    /**
     * Login using openid
     * @return boolean: TRUE if everything went OK
     */
    public function login()
    {
        try
        {
            if (!$this->_openid->mode)
            {
                header('Location: ' . $this->_openid->authUrl());
            }
            elseif ($this->_openid->mode != 'cancel')
            {
                if ($this->_openid->validate())
                {
                    $this->_id = $this->_openid->identity;
                    return TRUE;
                }
            }
        }
        catch (ErrorException $e)
        {
            return FALSE;
        }
        return FALSE;
    }

    public function getId()
    {
        return $this->_id;
    }

    /**
     * Gets an additional information given by the connection (if exists)
     * @param string $value The name of the attribute
     * @return string The attribute's value
     */
    public function getAttribute($value = '')
    {
        $attr = $this->_openid->getAttributes();
        return $attr[$value];
    }

    public function __destruct()
    {
        unset($this->_openid);
        unset($this->_id);
    }

    public function __tostring()
    {
        return $this->getId();
    }
}
//
// $openid = new OpenIdLogin();
// $openid->login();
// echo (string)$openid;
?>